<template>
  <div class="page-mark-top">
    <div class="header">
      <i class="iconfont icon-help" @click="helpVisible=true" title="帮助文档"></i>
      <Button type="primary" @click="view">预览</Button>
      <Button type="primary" @click="save">保存</Button>
      <Button type="success" @click="setData">定义数据源</Button>
    </div>

    <Modal width="700px" v-model="helpVisible" title="帮助文档" footer-hide class="visual-help-model">
      <p>
        <label for>布局：</label>
        可视化布局是采用了24栅格系统，将区域进行24等分，这样可以轻松应对大部分布局问题。使用栅格系统进行网页布局，可以使页面排版美观、舒适。
      </p>
      <div class="visual-help-footer">
        <Button type="primary" @click="helpVisible=false">确定</Button>
      </div>
    </Modal>

    <!-- 数据数据查看 -->
    <Modal
      width="700px"
      v-model="jsonEditVisual"
      title="数据查看/编辑"
      footer-hide
      class="visual-array-edit-model"
    >
      <div id="arrayEditHeader"></div>
      <div class="array-edit-footer">
        <Button @click="cancelHandler" style="margin-right:8px">取消</Button>
        <Button type="primary" @click="okHandler">确定</Button>
      </div>
    </Modal>

    <!-- 保存弹窗 -->
    <Modal width="340px" v-model="saveModalShow" title footer-hide class="visual-save-model">
      <div class="save-model-item">
        <span>模板名称</span>
        <Input v-model="componentName" placeholder="请输入模板名称" />
      </div>
      <div class="save-model-item">
        <span>模板描述</span>
        <Input v-model="componentDesc" placeholder="请输入模板描述" />
      </div>
      <div class="save-model-item">
        <span>结果字段</span>
        <Select v-model="resultKey">
          <Option v-for="(item,index) of keyList" :key="index" :value="item">{{item}}</Option>
        </Select>
      </div>
      <div class="save-model-item" v-if="version">
        <Checkbox v-model="updateVersion">是否更新版本</Checkbox>
      </div>
      <div class="save-edit-footer">
        <Button @click="saveCancel" style="margin-right:8px">取消</Button>
        <Button type="primary" @click="saveOk">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { saveTemplate, updateTemplateByVersion, createVersion } from 'http/api/mark'
import { saveListDetail } from 'http/api/linemanage'
import { routePathData } from 'assets/scripts/common'
import bus from 'assets/scripts/bus';

export default {
  computed: {
    ...mapState({
      components: state => state.mark.components,
      layout: state => state.mark.layout,
      source: state => state.mark.source,
      grid: state => state.mark.grid
    })
  },
  data () {
    return {
      helpVisible: false,
      jsonEditVisual: false,
      arrayEditor: null,
      componentName: '', // 组件名称
      componentDesc: '', // 组件描述
      componentId: '',
      saveModalShow: false,
      resultKey: '',
      keyList: [],
      version: null,
      updateVersion: false
    };
  },
  methods: {
    ...mapActions(['setSource']),

    // 设置编辑的数据
    setHeaderData ({ desc, id, name, resultKey }) {
      this.componentName = name;
      this.componentDesc = desc;
      this.componentId = id;
      this.resultKey = resultKey;
    },

    // 设置数据源的数据
    setData () {
      this.jsonEditVisual = true;

      if (!this.arrayEditor) {
        this.arrayEditor = new this.$jsoneditor(
          document.getElementById('arrayEditHeader'),
          {
            search: false,
            mode: 'text',
            indentation: 2
          }
        );
      }

      this.arrayEditor.set(this.source);
    },

    // 确定编辑
    okHandler () {
      try {
        let value = this.arrayEditor.get();
        this.setSource(value);
        this.cancelHandler();
      } catch (err) {
        console.log(err);
        this.$Message.error('请输入正确的数据');
      }
    },

    // 取消编辑
    cancelHandler () {
      this.jsonEditVisual = false;
    },

    // 数据保存
    save () {
      // 判断组件key的唯一性
      let keys = new Set();
      this.components.forEach(item => {
        keys.add(item.key)
      });

      if (keys.size !== this.components.length) {
        this.$Message.error('存在key值相同的组件，不可保存');
        return false;
      }

      if (this.components && this.components.length === 0) {
        this.$Message.error('没有可保存的组件');
        return false;
      }

      // key确定
      this.keyList = [];
      this.components.forEach(item => {
        if (item.saveResult) {
          this.keyList.push(item.key)
        }
      })

      this.saveModalShow = true;
    },

    // 取消保存
    saveCancel () {
      this.saveModalShow = false;
    },

    // 确定保存
    saveOk () {
      if (!this.componentName) {
        this.$Message.error('请输入模板名称');
        return false;
      }
      if (!this.componentDesc) {
        this.$Message.error('请输入模板描述');
        return false;
      }

      let result = {
        name: this.componentName,
        desc: this.componentDesc
      }

      let config = {
        components: JSON.stringify(this.components),
        layout: JSON.stringify(this.layout),
        source: JSON.stringify(this.source),
        grid: JSON.stringify(this.grid),
        resultKey: this.resultKey,
        name: this.componentName,
        desc: this.componentDesc
      }

      // 编辑
      if (this.componentId && this.version) {
        updateTemplateByVersion({ config, id: this.componentId, version: this.version }).then(res => {
          this.sureEdit(this.componentId, config)
        }).catch(err => {
          this.$Message.error(err)
        })
      } else {
        // 新增
        saveTemplate(result).then(async res => {
          // 执行新建业务线
          // let newBusinessType = await this.newBusiness(res.data.id)
          // if (!newBusinessType) return; // 新建任务失败

          // 第一次创建自动创建版本号
          this.createVersion(res.data.id, config)
          this.componentName = ''
          this.componentDesc = ''
          this.$Message.success('保存成功')

          // 跳转到模板管理页面
          this.$router.push({
            path: routePathData.templateManage
          })
        }).catch(err => {
          console.log(err)
        })
      }
    },

    // 确认编辑
    sureEdit (id, config) {
      this.componentName = ''
      this.componentDesc = ''
      this.componentId = ''
      this.$Message.success('编辑成功');

      if (this.updateVersion) {
        // 需要更新版本
        this.createVersion(id, config)
        this.$router.push({
          path: routePathData.templateManage
        })
      } else {
        this.$router.push({
          path: routePathData.templateManage
        })
      }
    },

    // 创建版本号
    createVersion (id, config) {
      return createVersion({
        id,
        config
      }).then(res => {
        return true
      })
        .catch(err => {
          console.log(err)
        })
    },

    // 新建业务线
    async newBusiness (templateId) {
      let businessConfig = {
        // 新增和编辑需要传递的参数
        modeName: this.componentName, // 业务名称
        modelId: '',
        modelType: 'task', // 类型配置
        describe: '', // 简短描述
        tasks: {
          createBatchTaskFlowId: '',
          taskExportTaskFlowId: '',
          recoveryStrategy: '',
          transferStrategy: '',
          createMedalTaskFlowId: '',
          integralHandle: ''
        },
        views: {
          viewMarkPage: `/home/mark-page/${templateId}`,
          viewCreateBatch: `/home/create-batch/${templateId}`,
          viewCreateMedal: `/home/create-medal/${templateId}`,
          viewExport: `/home/export/${templateId}`,
          viewMarkTaskPage: `/home/marktask-detail/${templateId}`,
          viewMedalPage: `/home/medal-page/${templateId}`,
          viewMyIntegralDetail: `/home/myintegral-detail/${templateId}`,
          viewResultPage: `/home/result-page/${templateId}`
        },
        flowTask: [],
        markTemplateId: templateId, // 自定义模板id
        businessBatchConfig: [] // 业务线创建批次配置
      }
      return saveListDetail({
        id: businessConfig.modelId,
        modelType: businessConfig.modelType,
        data: businessConfig
      }).then(res => {
        return true;
      })
        .catch(err => {
          this.$Message.error('添加失败，快看看接口咋地了？详细信息：' + err)
          return false;
        })
    },

    // 数据预览
    view () {
      console.log(this.layout)
      console.log(this.components)

      // 记录去的是预览页面
      sessionStorage.setItem('fromPreview', true)
      this.$router.push('/home/mark/preview');
    }
  },
  mounted () {
    this.version = this.$route.query.version || ''
    bus.$on('setHeaderData', this.setHeaderData);
  },
  beforeDestroy () {
    bus.$off('setHeaderData', this.setHeaderData);
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
@import '../../assets/theme/themeBlue.less';
.page-mark-top {
  height: 50px;
  border-bottom: #e6e6e6 1px solid;
  button {
    float: right;
    margin-right: 10px;
  }
  .header {
    overflow: hidden;
    position: relative;
    top: 9px;
  }
  .icon-help {
    float: right;
    font-size: 20px;
    position: relative;
    top: 0px;
    margin-right: 10px;
    cursor: pointer;
    &:hover {
      color: @primary;
    }
  }
}
</style>

<style lang="less">
.visual-help-model {
  p {
    line-height: 26px;
    margin-bottom: 20px;
    label {
      font-weight: bold;
    }
  }
  .ivu-modal-body {
    padding-bottom: 72px;
  }
  .visual-help-footer {
    float: right;
    margin-top: 20px;
  }
}
.visual-save-model {
  .ivu-modal-body {
    padding-bottom: 72px;
  }
  .save-model-item {
    margin-top: 8px;
    span {
      margin-bottom: 2px;
      display: inline-block;
    }
  }
  .save-edit-footer {
    float: right;
    margin-top: 20px;
  }
  .ivu-input,
  .ivu-select {
    width: 300px;
  }
}
</style>
